package dem3;

import java.util.*;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-05-16
 * Time: 22:11
 */
public class Test {

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        set.contains(6);
        for (Integer x : set) {

        }
        Set<Character> set1 = new HashSet<>();
        String str = "ewd";
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
        }

        Map<String,String> map = new HashMap<>();
        Set<Map.Entry<String,String>> set2 = map.entrySet();
        Map<Node,Node> map1 = new HashMap<>();

        String[] strs = {"i", "love", "leetcode", "i", "love", "coding"};
        //String[] str = {"a","b","c","c"};
        List<String> list = topKFrequent(strs,1);
        System.out.println(list);
//        int n = "i".compareTo("love");
//        System.out.println(n);
    }

    public static List<String> topKFrequent(String[] words, int k) {

        Map<String, Integer> map = new HashMap<>();
        for (String str : words) {
            if (map.containsKey(str)){
                int tmp = map.get(str);
                map.put(str,tmp + 1);
            }else {
                map.put(str,1);
            }
        }

        PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                int n = o1.getValue().compareTo(o2.getValue());
                if (n == 0){
                    return o2.getKey().compareTo(o1.getKey());
                }
                return n;
            }
        });
        int n = k;
        for (Map.Entry<String,Integer> entry : map.entrySet()) {
            if (k > 0){
                k--;
                queue.add(entry);
                continue;
            }
            Map.Entry<String,Integer> tmp = queue.peek();
            if(entry.getValue().compareTo(tmp.getValue()) == 0){
                int num = entry.getKey().compareTo(tmp.getKey());
                if (num < 0){
                    queue.poll();
                    queue.add(entry);
                }
            }else {
                if (entry.getValue().compareTo(tmp.getValue()) > 0){
                    queue.poll();
                    queue.add(entry);//
                }
            }
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < n; i++){
            String str = queue.poll().getKey();
            list.add(str);
        }
        Collections.reverse(list);
        return list;
    }

}
